//
//  CAPUserAccountTools.swift
//  CAPSwift
//
//  Created by captain on 16/4/20.
//  Copyright © 2016年 captain. All rights reserved.
//

import UIKit

class CAPUserAccountTools: NSObject {

    static let sharedTools: CAPUserAccountTools = CAPUserAccountTools()
    
    //用户头像路径
    var userAccountModel: CAPOauthModel?
    
    //用户是否登录
    var isLogin: Bool {
        if userAccountModel?.access_token != nil{
            return true
        }else{
            return false
        }
        
    }
    
    //访问令牌
    var accessToken: String? {
        if userAccountModel?.access_token != nil{
            //没有过期
            if !isExpired {
                return userAccountModel?.access_token
                //过期
            }else{
                return nil
            }
            
            //第一次没有token
        }else{
            return nil
        }
    }
    
    //判断是否过期
    var isExpired: Bool{
        let date = userAccountModel?.expires_date
        
        if date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            return false
        }else{
            return true
        }
    }
    
    //路径
    let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archiver")
    
    // MARK: - 重新init
    override init() {
        super.init()
        
        userAccountModel = getUserInfo()
    }
    //保存用户数据
    func saveUserInfo(model: CAPOauthModel){
        //保存之前要先赋值model
        userAccountModel = model
        
        
        NSKeyedArchiver.archiveRootObject(model, toFile: path)
    }
    
    //获取用户数据
    func getUserInfo() -> CAPOauthModel?{
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? CAPOauthModel
        
        return result
    }
    
    
}
